package com.sxw.hw_student.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxw.hw_student.system.entity.SysRoleMenu;
import com.sxw.hw_student.system.entity.SysUserRole;
import com.sxw.hw_student.system.service.ISysRoleMenuService;
import com.sxw.hw_student.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/roleMenu")
public class SysRoleMenuController {

    @Autowired
    private ISysRoleMenuService service;
    @Autowired
    private ISysUserRoleService userRoleService;

    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(required = false) Long roleId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size) {

        QueryWrapper<SysRoleMenu> wrapper = new QueryWrapper<>();
        if (roleId != null) {
            wrapper.eq("role_id", roleId);
        }

        Page<SysRoleMenu> pageResult = service.page(new Page<>(page, size), wrapper);

        Map<String, Object> response = new HashMap<>();
        response.put("data", pageResult.getRecords());
        response.put("total", pageResult.getTotal());
        response.put("currentPage", pageResult.getCurrent());
        response.put("totalPages", pageResult.getPages());

        return ResponseEntity.ok(response);
    }

    @PutMapping("/update")
    public void update(@RequestBody SysRoleMenu roleMenu) {
        service.updateById(roleMenu);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Integer id) {
        service.removeById(id);
    }

    @PostMapping("/assign")
    public ResponseEntity<?> assignMenusToUsers(@RequestBody Map<String, List<Integer>> request) {
        List<Integer> menuIds = request.get("menuIds");
        List<Integer> userIds = request.get("userIds");

        if (menuIds == null || userIds == null || menuIds.isEmpty() || userIds.isEmpty()) {
            return ResponseEntity.badRequest().body("菜单或用户列表不能为空");
        }

        Set<SysRoleMenu> roleMenusToSave = new HashSet<>();

        for (Integer userId : userIds) {
            List<SysUserRole> userRoles = userRoleService.list(
                    new QueryWrapper<SysUserRole>().eq("user_id", userId));

            for (SysUserRole userRole : userRoles) {
                Long roleId = userRole.getRoleId();
                for (Integer menuId : menuIds) {
                    SysRoleMenu roleMenu = new SysRoleMenu();
                    roleMenu.setRoleId(roleId.intValue());
                    roleMenu.setMenuId(menuId);
                    roleMenusToSave.add(roleMenu);
                }
            }
        }

        for (SysRoleMenu rm : roleMenusToSave) {
            service.remove(new QueryWrapper<SysRoleMenu>()
                    .eq("role_id", rm.getRoleId()).eq("menu_id", rm.getMenuId()));
        }

        boolean result = service.saveBatch(new ArrayList<>(roleMenusToSave));
        return result ? ResponseEntity.ok("分配成功") : ResponseEntity.status(500).body("分配失败");
    }
}